<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Member extends Stourweb_Controller{

    /*
     * 会员配置总控制器
     *
     */
    public function before()
    {

        parent::before();
        $action = $this->request->action();

        if($action == 'index')
        {

            $param = $this->params['action'];
            $right = array(
                'read'=>'slook',
                'save'=>'smodify',
                'delete'=>'sdelete',
                'update'=>'smodify'
            );
            $user_action = $right[$param];
            if(!empty($user_action))
                Common::getUserRight('member',$user_action);


        }
        if($action == 'add')
        {
            Common::getUserRight('member','sadd');
        }
        if($action == 'edit')
        {
            Common::getUserRight('member','smodify');
        }
        if($action == 'ajax_save')
        {
            Common::getUserRight('member','smodify');
        }
        $this->assign('parentkey',$this->params['parentkey']);
        $this->assign('itemid',$this->params['itemid']);


    }

    public function action_index()
    {

        $action=$this->params['action'];
        $reg_from_data = Model_Member::$_reg_from_arr;
        $this->assign('reg_from_data',$reg_from_data);
        if(empty($action))  //显示列表
        {
            $msg = '';
            if(St_Functions::is_normal_app_install('ebooking')){
                $msg .= '如果当前会员是同业端采购商，删除将一并删除采购商账户！<br/>';
            }
            if(St_Functions::is_normal_app_install('cshop')){
                $msg .= '如果当前会员是云店管理员，删除将一并删除云店管理员的账户！<br/>';
            }
            $msg .= '确定删除吗？';

            $this->assign('notice_msg',$msg);
            $this->display('stourtravel/member/list');
        }
        else if($action=='read')    //读取列表
        {

            $reg_from=Common::remove_xss(Arr::get($_GET,'reg_from'));
            $start=Common::remove_xss(Arr::get($_GET,'start'));
            $limit=Common::remove_xss(Arr::get($_GET,'limit'));
            $keyword=Common::remove_xss(Arr::get($_GET,'keyword'));
            $sort = json_decode(Common::remove_xss(Arr::get($_GET, 'sort')));
            $sex =Common::remove_xss(Arr::get($_GET,'sex'));
            $verifystatus = Common::remove_xss(Arr::get($_GET,'verifystatus'));
            if(is_null($sort)){
                $order='order by a.jointime desc';
            }else{
                if($sort[0]->property=='virtual')
                {
                    $sort[0]->property = 'is_virtual';
                }
                $order="order by a.".$sort[0]->property." ".$sort[0]->direction;
            }
            if(!empty($keyword))
            {
                $w ="where (a.nickname like '%{$keyword}%' or a.email like '%{$keyword}%' or a.mobile like '%{$keyword}%')";
            }
            else
            {
                $w = 'where a.mid>0';
            }
            if($reg_from)
            {
                $reg_from = intval($reg_from);
                $w .= " and a.reg_from={$reg_from}";
            }
            if($verifystatus != -1 && $verifystatus != '')
            {
                $w .= " and a.verifystatus={$verifystatus}";
            }
           if($sex)
           {
               $w .= " and a.sex='$sex'";
           }
			//虚拟会员过滤
			$virtual = Arr::get($_GET, 'virtual');
           if($virtual)
           {
               $w .= " and a.is_virtual='$virtual'";
           }
            $sql="select a.*  from sline_member as a $w $order limit $start,$limit";
            //echo $sql;
            $totalcount_arr=DB::query(Database::SELECT,"select count(*) as num from sline_member a " . $w)->execute()->as_array();
            $list=DB::query(Database::SELECT,$sql)->execute()->as_array();
            $new_list=array();
            foreach($list as $k=>$v)
            {
                if (St_Functions::is_normal_app_install('system_wallet')) {
                    $wallet = DB::select()->from('wallet_member')->where('member_id','=',$v['mid'])->execute()->current();
                    $remain_amount = $wallet['remain_amount']?:0;
                    $v['money'] = bcadd($v['money'],$remain_amount,2);
                }
                $v['jointime'] = Common::myDate('Y-m-d',$v['jointime']);
                $v['logintime'] = empty($v['logintime']) ? '' : Common::myDate('Y-m-d H:i',$v['logintime']);
                $v['id'] = $v['mid'];
                $rank = Model_Member::member_rank($v['mid'],array('return'=>1));
                $v['rank'] = $rank['current_rank'];
                $v['reg_from'] = Model_Member::member_reg_from($v['reg_from']);
                $new_list[] = $v;
            }
            $result['total']=$totalcount_arr[0]['num'];
            $result['lists']=$new_list;
            $result['success']=true;

            echo json_encode($result);
        }
        else if($action=='save')   //保存字段
        {

        }
        else if($action=='delete') //删除某个记录
        {
            $rawdata=file_get_contents('php://input');
            $data=json_decode($rawdata);
            $id=$data->id;

            if(is_numeric($id)) //
            {
                $m_info = DB::select()->from("member")->where("mid={$id}")->execute()->current();
                $model=ORM::factory('member',$id);
                $model->delete_clear();
                //会员附件表
                DB::delete('member_third')->where("mid={$id}")->execute();

                if($m_info['mobile']){
                    $is_exist = DB::select()->from("purchaser")->where("link_phone={$m_info['mobile']}")->execute()->current();
                    if($is_exist){
                        DB::update('purchaser')->set(array('is_delete'=>1))->where("id={$is_exist['id']}")->execute();
                        DB::update('purchaser_staff')->set(array('is_delete'=>1))->where("purchaser_id={$is_exist['id']}")->execute();
                    }
                }

            }
        }
        else if($action=='update')//更新某个字段
        {
            $id=Arr::get($_POST,'id');
            $field=Arr::get($_POST,'field');
            $val=Arr::get($_POST,'val');

            $value_arr[$field] = $val;
            $isupdated = DB::update('member')->set($value_arr)->where('mid','=',$id)->execute();
            if($isupdated)
                echo 'ok';
            else
                echo 'no';
        }
    }

    /*
     * 添加会员
     * */
    public function action_add()
    {
        $info['litpic'] =  $GLOBALS['cfg_public_url'] . 'images/member_nopic.png';
        $this->assign('info',$info);
        $this->assign('action','add');
        if($this->params['virtual'] == 1)
        {
            $this->display('stourtravel/member/add_virtual');
        }
        else
        {
            $this->display('stourtravel/member/add');
        }
    }

    //简单新增
    public function action_simple_add()
    {
        $info['litpic'] =  $GLOBALS['cfg_public_url'] . 'images/member_nopic.png';
        $this->assign('info',$info);
        $this->assign('action','add');
        $this->display('stourtravel/member/simple_add');
    }
    /*
     * 修改会员
     * */
    public function action_edit()
    {
        $mid = $this->params['mid'];//会员id.
        $this->assign('action','edit');
        $info = DB::select()->from('member')->where('mid','=',$mid)->execute()->current();
        if(empty($info['litpic']))
        {
            $info['litpic'] =  $GLOBALS['cfg_public_url'] . 'images/member_nopic.png';
        }

        $menu_id = DB::select('id')->from('menu_new')->where('title','=','实名认证')->execute()->get('id');
        $this->assign('meunid',$menu_id);
        $info['reg_from_where'] = Model_Member::member_reg_from($info['reg_from']);
        $info['grade'] = Common::member_rank($mid,array('return'=>'rankname'));
        $info['birth_date'] = explode('/',$info['birth_date']);
        if(St_Functions::is_normal_app_install('system_guide'))
        {
            $check_is_guide = DB::select('id')->from('guide')->where('mid','=',$mid)->execute()->current();
            if($check_is_guide)
            {
                $guide_menuid = DB::select('id')->from('menu_new')->where('title','=','导游列表')->execute()->get('id');
                $this->assign('guide_menuid',$guide_menuid);
                $info['is_guide'] = 1;//是导游
                $info['guide_id'] = $check_is_guide['id'];
            }
            else
            {
                $info['is_guide'] = 2;//不是导游
            }
        }

        $cfg_member_reg_company_required = Model_Sysconfig::get_configs(0,'cfg_member_reg_company_required',true);
        $cfg_member_reg_company_field_name = Model_Sysconfig::get_configs(0,'cfg_member_reg_company_field_name',true);

        $this->assign('cfg_member_reg_company_required',$cfg_member_reg_company_required);
        $this->assign('cfg_member_reg_company_field_name',$cfg_member_reg_company_field_name);

        $this->assign('info',$info);
        $this->display('stourtravel/member/edit');
    }
    /*
     * 保存
     * */
    public function action_ajax_save()
    {
        $action = Arr::get($_POST,'action');//当前操作
        $id = Arr::get($_POST,'mid');
        $status = false;
        //添加操作
        if($action == 'add' && empty($id))
        {
            $model = ORM::factory('member');
            $model->jointime = time();
            $model->email = Arr::get($_POST,'email');
            $model->mobile = Arr::get($_POST,'mobile');
            $model->identity = '0';
        }
        else
        {
            $identity = DB::select()->from('member')->where("mid={$id}")->execute()->get('identity');
            $model = ORM::factory('member')->where('mid','=',$id)->find();
            if($identity){
                $identity = explode(',',$identity);
                if(!in_array(0,$identity)){
                    array_push($identity,0);
                }
                $model->identity = implode(',',$identity);
            }else{
                $model->identity = '0';
            }
        }
        $pwd = Arr::get($_POST,'password');
        if($pwd)
        {

            $model->pwd = md5(Arr::get($_POST,'password'));
        }

		$model->logintime = time();
		$model->truename =Arr::get($_POST,'truename');
        $model->nickname = Arr::get($_POST,'nickname');
        $model->sex = Arr::get($_POST,'sex');
        $bairth_year = Arr::get($_POST,'bairth_year');
        $bairth_month = Arr::get($_POST,'bairth_month');
        $bairth_day = Arr::get($_POST,'bairth_day');
        $birth_date = $bairth_year.'/'.$bairth_month.'/'.$bairth_day;
        $model->birth_date = $birth_date;
        $model->constellation = Arr::get($_POST,'constellation');
        $model->wechat = Arr::get($_POST,'wechat');
        $model->qq = Arr::get($_POST,'qq');
        $model->native_place = Arr::get($_POST,'native_place');
        $model->signature = Arr::get($_POST,'signature');
        $model->company_name = $_POST['company_name'];
        $model->remarks = $_POST['remarks'];
        if($action=='add' && empty($id))
        {
            $model->create();
        }
        else
        {
            $model->update();
        }

        if($model->saved())
        {
            if($action=='add')
            {
                $productid = $model->mid; //插入的产品id
            }
            else
            {
                $productid =null;
            }

            $status = true;
        }
        echo json_encode(array('status'=>$status,'productid'=>$productid));

    }

	/**
     *  添加虚拟用户
     */
    public function action_ajax_save_virtual()
    {

        $num = Arr::get($_POST, 'num');

        //号码段
        $mobile_port = array("134", "135", "136", "137", "138", "139", "147", "150", "151", "152", "157", "158", "159", "187", "188", "130", "131", "132", "155", "156", "186", "133", "153", "180","182", "189");
        //密码
        $password = md5('stourweb_cms');
        //随机数组
		for($i=0;$i<$num;$i++)
		{
			$rand_num[$i] = array_rand($mobile_port, 1);
		}

		if(is_array($rand_num))
		{
			//$model = ORM::factory('member');
			foreach ($rand_num as $k)
			{
				$time = time();
				$name = $mobile_port[$k] . rand(10, 99) . '***';
				$insert_arr = array(
					'nickname' => $name,
					'pwd' => $password,
					'truename' => $name,
					'litpic' => self::rand_litpic(),
					'is_virtual' => 2,
					'jointime' => $time,
					'logintime' => $time,
				);
				
				DB::insert('member', array_keys($insert_arr))->values(array_values($insert_arr))->execute();

			}
		}
		else
		{
			$time = time();
			$name = $mobile_port[$rand_num] . rand(10, 99) . '***';
			$insert_arr = array(
				'nickname' => $name,
				'pwd' => $password,
				'truename' => $name,
				'litpic' => '/uploads/member_nopic.png',
				'is_virtual' => 2,
				'jointime' => $time,
				'logintime' => $time,
			);
				
			DB::insert('member', array_keys($insert_arr))->values(array_values($insert_arr))->execute();

		}
        echo json_encode(array('status'=>true));
    }
	
	/**
	 *	随机封面图
	 */
	public function rand_litpic()
	{
		$imgList='';

		$cacheFile = APPPATH . 'cache/headFile.php';
		if(file_exists($cacheFile))
		{
			$imgList = require($cacheFile);
		}
		else
		{
			$imgFolder = '../uploads/head/';
			mt_srand((double)microtime()*1000);
			
			$imgs = dir($imgFolder);

			while ($file = $imgs->read()) 
			{
				if (preg_match("gif", $file) || preg_match("jpg", $file) || preg_match("png", $file))
				{
					$imgList .= "$file ";
				}
			} 
			
			closedir($imgs->handle);
			
			$imgList = explode(" ", $imgList);

			$imgList = array_filter($imgList);

			$fileData = var_export($imgList, 1);
			file_put_contents($cacheFile, "<?php\r\nreturn " . $fileData . ';');
		}

		$no = count($imgList)-1;
		
		$random = mt_rand(0, $no);
		$image = $imgList[$random];


		return '/uploads/head/' . $image;
	}

    /*
     * ajax检测是否存在
     * */
    public function action_ajax_check()
    {
        $field = $this->params['type'];
        $val = Arr::get($_POST,'val');//值
        $mid = Arr::get($_POST,'mid');//会员id
        $flag = Model_Member::checkExist($field,$val,$mid);
        echo $flag;
    }

   /*
    * 会员订单查看
    * */
    public function action_vieworder()
    {
        $mid = $this->params['mid'];
        $list = DB::select()->from('member_order')->where('memberid','=',$mid)->execute()->as_array();

        $this->assign('orderlist',$list);
        $this->display('stourtravel/member/orderlist');
        
    }


    /**
     * 注册协议
     */
    public function action_agreement()
    {
        $fields = array('cfg_member_agreement_open','cfg_member_agreement_title','cfg_member_agreement');
        $config = Model_Sysconfig::get_configs(0,$fields);
        $this->assign('config',$config);
        $this->display('stourtravel/member/agreement');
    }

    /**
     * 弹出框选择会员
     */
    public function action_dialog_member_list()
    {
        $action=$this->params['action'];
        if(empty($action))  //显示列表
        {
            $this->assign('virtual',$this->params['virtual']);
            $this->display('stourtravel/member/dialog_member_list');
        }
        else if($action=='read')    //读取列表
        {
            $start=Arr::get($_GET,'start');
            $limit=Arr::get($_GET,'limit');
            $keyword=Arr::get($_GET,'keyword');
            $sort = json_decode(Arr::get($_GET, 'sort'));
            if(is_null($sort)){
                $order='order by a.jointime desc';
            }else{
                $order="order by a.".$sort[0]->property." ".$sort[0]->direction;
            }
            $w='where a.mid>0 ';
            if(!empty($keyword))
            {
                $w .="and (a.nickname like '%{$keyword}%' or a.email like '%{$keyword}%' or a.mobile like '%{$keyword}%')";
            }
            if(isset($_GET['virtual']) && $_GET['virtual']==0){
                $w .= " and a.is_virtual!=2 ";
            }

            $sql="select a.*  from sline_member as a $w $order limit $start,$limit";
            $totalcount_arr=DB::query(Database::SELECT,"select count(*) as num from sline_member a $w")->execute()->as_array();
            $list=DB::query(Database::SELECT,$sql)->execute()->as_array();
            $new_list=array();
            foreach($list as $k=>$v)
            {
                $v['logintime'] = Common::myDate('Y-m-d',$v['logintime']);
                $v['id'] = $v['mid'];
                $new_list[] = $v;
            }
            $result['total']=$totalcount_arr[0]['num'];
            $result['lists']=$new_list;
            $result['success']=true;
            echo json_encode($result);
        }

    }


    /**
     * @function  会员实名认证列表
     */
    public function action_verifystatus_list()
    {
        $menu_id = DB::select('id')->from('menu_new')->where('title','=','实名认证')->execute()->get('id');
        $this->assign('meunid',$menu_id);
        $action=$this->params['action'];
        if(empty($action))  //显示列表
        {
            $this->display('stourtravel/member/verifystatus/verifystatus_list');
        }
        else if($action=='read')    //读取列表
        {
            $start=Arr::get($_GET,'start');
            $limit=Arr::get($_GET,'limit');
            $keyword=Arr::get($_GET,'keyword');
            $sort = json_decode(Arr::get($_GET, 'sort'));
            $sex = Arr::get($_GET,'sex');
            $verifystatus = Arr::get($_GET,'verifystatus');
            if(is_null($sort)){
                $order='order by CASE WHEN a.verifystatus = 0 THEN 9999 ELSE IFNULL(a.verifystatus, 9999) END ASC,a.jointime desc';
            }else{
                $order="order by a.".$sort[0]->property." ".$sort[0]->direction;
            }
            if(!empty($keyword))
            {
                $w ="where (a.nickname like '%{$keyword}%' or a.email like '%{$keyword}%' or a.mobile like '%{$keyword}%')";
            }
            else
            {
                $w = 'where a.mid>0';
            }
            if(!is_null($verifystatus) && $verifystatus!='all'){
                $w .= " and a.verifystatus=".$verifystatus;
            }
            if($sex)
            {
                $w .= " and a.sex='$sex'";
            }
            $sql="select a.*  from sline_member as a $w $order limit $start,$limit";
            //echo $sql;
            $totalcount_arr=DB::query(Database::SELECT,"select count(*) as num from sline_member a $w")->execute()->as_array();
            $list=DB::query(Database::SELECT,$sql)->execute()->as_array();
            $new_list=array();
            foreach($list as $k=>$v)
            {
                $v['logintime'] = Common::myDate('Y-m-d',$v['logintime']);
                $v['id'] = $v['mid'];
                $new_list[] = $v;
            }
            $result['total']=$totalcount_arr[0]['num'];
            $result['lists']=$new_list;
            $result['success']=true;

            echo json_encode($result);
        }
        else if($action=='check')   //审核
        {
            $mid = Arr::get($_GET,'mid');
            $info = DB::select()->from('member')->where('mid','=',$mid)->execute()->current();
            $info['idcard_pic'] = (array)json_decode($info['idcard_pic']);
            $this->assign('info',$info);
            $this->display('stourtravel/member/verifystatus/verifystatus_check');
        }
        else if($action=='do_check')
        {
            $mid = Arr::get($_GET,'mid');
            $status = Arr::get($_POST,'status');
            if($status==1)
            {

                $cardid = DB::select('cardid')->from('member')->where('mid','=',$mid)->execute()->get('cardid');
                $cardinfo = Common::check_idcard($cardid);
                if(!$cardinfo)
                {
                    echo json_encode(array('status'=>0));
                    return false;
                }
                else
                {
                    $cardinfo['verifystatus'] = 2;
                    DB::update('member')->set($cardinfo)->where('mid','=',$mid)->execute();
                    echo json_encode(array('status'=>1,'type'=>2));
                }

            }
            else
            {
                DB::update('member')->set(array('verifystatus'=>3))->where('mid','=',$mid)->execute();
                echo json_encode(array('status'=>1,'type'=>3));
            }

        }
        else if($action=='modify'||$action=='show') //认证详情
        {
            $mid = Arr::get($_GET,'mid');
            $info = DB::select()->from('member')->where('mid','=',$mid)->execute()->current();
            $info['idcard_pic'] = (array)json_decode($info['idcard_pic']);
            $this->assign('info',$info);
            $this->assign('action',$action);
            $this->display('stourtravel/member/verifystatus/verifystatus_edit');
        }
        else if($action=='do_modify')
        {
            $status = false;
            $mid = Arr::get($_POST,'mid');
            $verifystatus = Arr::get($_POST,'verifystatus');
            $truename = Arr::get($_POST,'truename');
            $cardid = Arr::get($_POST,'cardid');
            $front_pic = Arr::get($_POST,'front_pic');
            $verso_pic = Arr::get($_POST,'verso_pic');
            $uptate_arr = array(
                'verifystatus'=>$verifystatus,
                'cardid'=>$cardid,
                'truename'=>$truename,
                'idcard_pic'=>json_encode(array('front_pic'=>$front_pic,'verso_pic'=>$verso_pic)),
            );

            $rsn = DB::update('member')->set($uptate_arr)->where('mid','=',$mid)->execute();

            if($rsn!==false)
            {
                $status = true;
            }
            echo json_encode(array('status'=>$status));
            exit;

        }


    }


    public function action_verify_set()
    {
        $fields = array('cfg_member_force_verify');
        $config = Model_Sysconfig::get_configs(0,$fields);
        $this->assign('config',$config);
        $this->display('stourtravel/member/verify_set');
    }

    public function action_reg_field()
    {
        $fields = array('cfg_member_reg_company_field_name','cfg_member_reg_company_required');
        $config = Model_Sysconfig::get_configs(0,$fields);
        $this->assign('config',$config);
        $this->display('stourtravel/member/reg_field');
    }


    /**
     * 上传图片
     */
    public function action_ajax_upload_picture()
    {
        //if(!$this->request->is_ajax())exit;
        $filedata = Arr::get($_FILES, 'filedata');
        $storepath = UPLOADPATH . '/member/';
        if (!file_exists($storepath))
        {
            mkdir($storepath);
        }
        $filename = uniqid();
        $out = array();
        $ext = end(explode('.', $filedata['name']));

        if (move_uploaded_file($filedata['tmp_name'], $storepath . $filename . '.' . $ext))
        {
            $out['status'] = 1;
            $out['litpic'] = '/uploads/member/' . $filename . '.' . $ext;
        }
        echo json_encode($out);
    }

/*
     * 提现列表
     */
    public function action_withdraw()
    {
        $action = $this->params['action'];
        if (empty($action))  //显示列表
        {
            $this->display('stourtravel/member/withdraw');
        }
        else if ($action == 'read')    //读取列表
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');

            $order = 'order by a.addtime desc';
            $sort = json_decode($_GET['sort'], true);
            if(!empty($sort[0]))
            {
                $order = ' order by a.'.$sort[0]['property'].' '.$sort[0]['direction'].' ,a.addtime desc';
            }

            $w=" where a.id is not null ";
            if (!empty($keyword))
            {
                $w.= " and (a.bankcardnumber='{$keyword}' || a.bankaccountname like '%{$keyword}%' || b.nickname like '%{$keyword}%' || b.mobile='{$keyword}' || b.email='{$keyword}') ";
            }

            $sql = "select a.*,b.mobile,b.email,b.nickname from sline_member_withdraw a inner join sline_member b on a.memberid=b.mid {$w} {$order} limit {$start},{$limit}";
            $total  = DB::query(Database::SELECT, "select count(*) as num from sline_member_withdraw a inner join sline_member b on a.memberid=b.mid {$w}")->execute()->get('num');
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            $new_list = array();
            foreach ($list as $k => $v)
            {
                $v['account'] = empty($v['mobile'])?$v['email']:$v['mobile'];
                $v['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
                $v['finishtime'] =!empty($v['finishtime'])? date('Y-m-d H:i:s',$v['finishtime']):'';
                $v['status_name'] = Model_Member_Withdraw::get_status_name($v['status']);
                $new_list[] = $v;
            }
            $result['total'] = $total;
            $result['lists'] = $new_list;
            $result['success'] = true;

            echo json_encode($result);
        }

        else if ($action == 'delete') //删除某个记录
        {

        }
        else if ($action == 'update')//更新某个字段
        {

        }
    }
    /*
     * 交易记录
     */
    public function action_cashlog()
    {

        $action = $this->params['action'];
        if (empty($action))  //显示列表
        {
            $this->display('stourtravel/member/cashlog');
        }
        else if ($action == 'read')    //读取列表
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');

            $order = 'order by a.addtime desc';
            $sort = json_decode($_GET['sort'], true);
            if(!empty($sort[0]))
            {
               $order = ' order by a.'.$sort[0]['property'].' '.$sort[0]['direction'].' ,a.addtime desc';
            }

            $w=" where a.id is not null ";
            if (!empty($keyword))
            {
                $w.= " and (b.nickname like '%{$keyword}%' || b.mobile='{$keyword}' || b.email='{$keyword}') ";
            }

            $sql = "select a.*,b.mobile,b.email,b.nickname from sline_member_cash_log a inner join sline_member b on a.memberid=b.mid {$w} {$order} limit {$start},{$limit}";
            $total  = DB::query(Database::SELECT, "select count(*) as num from sline_member_cash_log a inner join sline_member b on a.memberid=b.mid {$w}")->execute()->get('num');
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            $new_list = array();
            foreach ($list as $k => $v)
            {
                $v['account'] = empty($v['mobile'])?$v['email']:$v['mobile'];
                $v['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
                $new_list[] = $v;
            }
            $result['total'] = $total;
            $result['lists'] = $new_list;
            $result['success'] = true;

            echo json_encode($result);
        }

        else if ($action == 'delete') //删除某个记录
        {

        }
        else if ($action == 'update')//更新某个字段
        {

        }
    }
    /*
     * 提现审核
     */
    public function action_withdraw_edit()
    {
        $id = $this->params['id'];
        $way_names = array('bank'=>'银行卡','alipay'=>'支付宝','weixin'=>'微信');
        $model = ORM::factory('member_withdraw',$id);
        $info = $model->as_array();

        $member_info = DB::select()->from('member')->where('mid','=',$info['memberid'])->execute()->current();
        $info['account'] = empty($member_info['mobile'])?$member_info['email']:$member_info['mobile'];
        $info['nickname'] = $member_info['nickname'];
        $info['way_name'] = $way_names[$info['way']];


        $this->assign('info',$info);
        $this->display('stourtravel/member/withdraw_edit');
    }
    /*
     * 审核保存
     */
    public function action_ajax_withdraw_save()
    {
        $id = $_POST['id'];
        $status = $_POST['status'];
        $audit_description = $_POST['audit_description'];

        $curtime = time();
        $db = Database::instance();
        $db->begin();
        try {
            $model = ORM::factory('member_withdraw', $id);
            if(!$model->loaded())
            {
                throw new Exception('提现不存在');
            }
            if ($model->status != 0) {
                throw new Exception('已审核过，不能重复审核');
            }
            if($status==$model->status)
            {
                throw new Exception('未改变审核状态');
            }

            $model->status = $status;
            $model->audit_description = $audit_description;
            $model->finishtime = $curtime;
            $model->save();
            if (!$model->saved())
            {
                throw new Exception('审核未成功，请重试');
            }
            $member_model = ORM::factory('member',$model->memberid);
            if(!$member_model->loaded())
            {
                throw new Exception('会员不存在');
            }

            $withdrawamount = floatval($model->withdrawamount);
            $money = floatval($member_model->money);
            $money_frozen = floatval($member_model->money_frozen);
            if($model->status==1)
            {
                if($withdrawamount>$money)
                {
                    throw new Exception('提现金额高于存款总额');
                }
                if($withdrawamount>$money_frozen)
                {
                    throw new Exception('提现金额高于冻结总额');
                }
                $member_model->money-=$withdrawamount;
                $member_model->money_frozen-=$withdrawamount;
                $member_model->save();
                if(!$member_model->saved())
                {
                    throw new Exception('审核未成功，请重试');
                }
                $log_des = '提现审核完成，解冻并扣除'.$withdrawamount.'元';
                $log_result = Model_Member_Cash_Log::add_log($member_model->mid,1,$withdrawamount,$log_des,array('withdrawid'=>$model->id));
                if(!$log_result)
                {
                    throw new Exception('审核未成功，请重试');
                }
            }
            else if($model->status==2)
            {
                if($withdrawamount>$money_frozen)
                {
                    throw new Exception('提现金额高于冻结总额');
                }
                $member_model->money_frozen-=$withdrawamount;
                $member_model->save();
                if(!$member_model->saved())
                {
                    throw new Exception('审核未成功，请重试');
                }
                $log_des = '提现审核未通过，解冻'.$withdrawamount.'元';
                $log_result = Model_Member_Cash_Log::add_log($member_model->mid,3,$withdrawamount,$log_des,array('withdrawid'=>$model->id));
                if(!$log_result)
                {
                    throw new Exception('审核未成功，请重试');
                }

            }

            $db->commit();
            echo json_encode(array('status'=>true,'msg'=>'审核完成'));

        }catch (Exception $excep)
        {
            $db->rollback();
            echo json_encode(array('status'=>false,'msg'=>$excep->getMessage()));
        }

    }

    /**
     * @function 导出excel页面
     */
    public function action_excel(){
        $this->display('stourtravel/member/excel');
    }

    /**
     * @function 导出会员
     */
    public function action_export_excel()
    {
        // 时间
        $starttime = empty($_GET['starttime'])? strtotime('-30 day'):strtotime($_GET['starttime'].' 00:00:00');
        $endtime =empty($_GET['endtime'])?time(): strtotime($_GET['endtime'].' 23:59:59');

        $where = 'WHERE 1 = 1';
        $where.= " and jointime >=  {$starttime} and jointime <= {$endtime} ";
        $sql = "SELECT *  FROM `sline_member` {$where} ORDER BY `jointime` DESC";

        $rows = DB::query(1, $sql)
                  ->execute()
                  ->as_array();

        $table = "<table><tr>";
        $table .= "<td>昵称</td>";
        $table .= "<td>真实姓名</td>";
        $table .= "<td>性别</td>";
        $table .= "<td>会员等级</td>";
        $table .= "<td>钱包总额</td>";
        $table .= "<td>邮箱</td>";
        $table .= "<td>手机号</td>";
        $table .= "<td>积分</td>";
        $table .= "<td>加入时间</td>";
        $table .= "<td>加入IP</td>";
        $table .= "<td>邮箱验证</td>";
        $table .= "<td>手机验证</td>";
        $table .= "<td>省份</td>";
        $table .= "<td>城市</td>";
        $table .= "<td>身份证号</td>";
        $table .= "<td>地址</td>";
        $table .= "<td>邮政编码</td>";
        $table .= "<td>备注</td>";
        $table .= "<td>注册类型</td>";
        $table .= "<td>出生年月</td>";
        $table .= "<td>星座</td>";
        $table .= "<td>QQ</td>";
        $table .= "<td>个性签名</td>";
        $table .= "<td>实名认证</td>";
        $table .= "<td>微信号</td>";
        $table .= "<td>籍贯</td>";
        $table .= "<td>冻结金额</td>";
        $table .= "<td>用户类型</td>";
        $table .= "</tr>";

        $verify_arr = array(
            0 => '未认证',
            1 => '审核中',
            2 => '已认证',
            3 => '未通过',
        );
        foreach ($rows as $row)
        {
            $table .= "<tr>";
            $table .= "<td>{$row['nickname']}</td>";
            $table .= "<td>{$row['truename']}</td>";
            $table .= "<td>{$row['sex']}</td>";
            $table .= "<td>" . Common::member_rank($row['mid'],array('return'=>'rankname')) . "</td>";
            $table .= "<td style='vnd.ms-excel.numberformat:@'>{$row['money']}</td>";
            $table .= "<td>{$row['email']}</td>";
            $table .= "<td style='vnd.ms-excel.numberformat:@'>{$row['mobile']}</td>";
            $table .= "<td style='vnd.ms-excel.numberformat:@'>{$row['jifen']}</td>";
            $jointime = $row['jointime'] ? date('Y-m-d H:i:s', $row['jointime']) : '';
            $table .= "<td>" . $jointime . "</td>";
            $table .= "<td>{$row['joinip']}</td>";
            $checkmail = $row['checkmail'] == 1 ? '已验证' : '未验证';
            $checkphone = $row['checkphone'] == 1 ? '已验证' : '未验证';
            $table .= "<td>". $checkmail ."</td>";
            $table .= "<td>". $checkphone ."</td>";
            $table .= "<td>{$row['province']}</td>";
            $table .= "<td>{$row['city']}</td>";
            $table .= "<td style='vnd.ms-excel.numberformat:@'>{$row['cardid']}</td>";
            $table .= "<td>{$row['address']}</td>";
            $table .= "<td style='vnd.ms-excel.numberformat:@'>{$row['postcode']}</td>";
            $table .= "<td>{$row['remarks']}</td>";
            $regtype = $row['regtype'] == 1 ? '邮箱' : '手机';
            $table .= "<td>". $regtype ."</td>";
            $table .= "<td>{$row['birth_date']}</td>";
            $table .= "<td>{$row['constellation']}</td>";
            $table .= "<td>{$row['qq']}</td>";
            $table .= "<td>{$row['signature']}</td>";
            $table .= "<td>" . $verify_arr[$row['verifystatus']] . "</td>";
            $table .= "<td>{$row['wechat']}</td>";
            $table .= "<td>{$row['native_place']}</td>";
            $table .= "<td style='vnd.ms-excel.numberformat:@'>{$row['money_frozen']}</td>";
            $virtual = $row['is_virtual'] == 1 ? '普通用户' : '虚拟用户';
            $table .= "<td>". $virtual ."</td>";
            $table .= "</tr>";
        }


        $table .= "</table>";
        $filename = date('Ymdhis');
        ob_end_clean();//清除缓冲区
        header('Pragma:public');
        header('Expires:0');
        header('Content-Type:charset=utf-8');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Content-Type:application/force-download');
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Type:application/octet-stream');
        header('Content-Type:application/download');
        header('Content-Disposition:attachment;filename=' . $filename . ".xls");
        header('Content-Transfer-Encoding:binary');

        $code = mb_detect_encoding($table, array('ASCII', 'GB2312', 'UTF-8'));
        if ($code != 'UTF-8')
        {
            $table = mb_convert_encoding($table, 'UTF-8', $code);
        }

        exit($table);
    }

    // 提现微信  支付宝
    public function action_ajax_withdraw_btn_save()
    {
        $id = $_POST['id'];
        $way = $_POST['way'];


        if($way == 'weixin')
        {
            $result = Model_Member_Withdraw::withdraw_weixin($id);
        }
        else
        {
            $result = Model_Member_Withdraw::withdraw_alipay($id);
        }
        echo json_encode($result);
    }

    //退款确认
    public function action_dialog_withdraw_check()
    {
        $this->display('stourtravel/member/dialog_withdraw_check');
    }
    /*
     * 会员积分
     * */
    public function action_jifen_list()
    {
        $mid = $this->params['mid'];//会员id.
        $this->assign('mid',$mid);
        $this->assign('action','jifen_list');
        $user_info=Model_Member::get_member_byid($mid);
        //总获得不包含退款
        $user_info['jifen_get_all'] = Model_Member_Jifen::member_get_total_jf($mid);
        //总的-剩余
        $user_info['jifen_used_all'] =Model_Member_Jifen::member_used_total_jf($mid);
        $this->assign('user_info',$user_info);

        $action = $this->params['act'];
        if (empty($action))  //显示列表
        {
            $this->display('stourtravel/member/jifen_list');
        }
        else if ($action == 'read')    //读取列表
        {
            $page = isset($_GET['page'])&& intval($_GET['page'])>0 ? intval($_GET['page']) : 1;
            $type = isset($_GET['type']) ? intval($_GET['type']) : 0;
            $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
            $obj = DB::select()->from('member_jifen_log')->where('memberid','=',$mid);
            if ($type)
            {
                $obj->where('type', '=', $type);
            }
            $total = count($obj->execute()->as_array());
            $result = $obj
                ->limit($limit)->offset(($page - 1) * $limit)
                ->order_by('addtime', 'desc')
                ->execute()
                ->as_array();
            foreach ($result as &$v)
            {
                $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
                $v['typeMsg'] = $v['type'] == 1 ? '使用' : '获取';
            }
            $data['list'] = $result;
            $data['total'] = $total;
            echo json_encode($data);
        }
        else if ($action == 'delete') //删除某个记录
        {

        }
        else if ($action == 'update')//更新某个字段
        {

        }
    }

    public function action_add_jifen()
    {
        $mid = $this->params['mid'];//会员id.
        $type = $this->params['type']==2?'增加':'减少';
        $this->assign('mid',$mid);
        $this->assign('action','add_jifen');
        $user_info=Model_Member::get_member_byid($mid);
        $user_info['jifen_get_all'] = Model_Member_Jifen::member_get_total_jf($mid);
        $user_info['jifen_used_all'] = Model_Member_Jifen::member_used_total_jf($mid);
        $this->assign('user_info',$user_info);
        $this->assign('type',$type);
        $action = $this->params['act'];
        if (empty($action))  //显示列表
        {
            $this->display('stourtravel/member/jifen_add');
        }
        else if ($action == 'save') //保存
        {
            $return=array(
                'status'=>0
            );
            $mid = intval($_POST['mid']);
            $jifen = intval($_POST['jifen']);
            $type = $_POST['type'];
            if($type=='增加'){
                $t = 2;
                $sql = "UPDATE `sline_member` SET jifen=jifen+{$jifen} WHERE mid={$mid}";
            }else{
                $t = 3;
                $sql = "UPDATE `sline_member` SET jifen=jifen-{$jifen} WHERE mid={$mid}";
            }
            $flag = DB::query(Database::UPDATE, $sql)->execute();
            if ($flag)
            {
                $content = "管理员{$type} {$jifen} 积分";
                Model_Member_Jifen::add_jifen_log($mid, $content, $jifen, $t);
                $return['status']=1;
                $return['type']=$type;
            }
            echo json_encode($return);exit;
        }
    }

    /*
     * 异步获取相关统计数据
     * */
    public function action_ajax_sell_info()
    {
        $mid = $this->params['mid'];//会员id.

        $out = array();
        $where="a.memberid={$mid}";
        $sql = "SELECT a.* FROM `sline_member_order` a LEFT JOIN `sline_member` b ON(a.memberid=b.mid)  WHERE $where  ORDER BY a.addtime DESC ";
        //订单总数
        $totalSql = "SELECT count(*) as dd " . strchr($sql, " FROM");
        $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by
        $totalN = DB::query(1, $totalSql)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? intval($totalN[0]['dd']) : 0;
        $out['total_num'] = $totalNum;
        $arr = DB::query(1, $sql)->execute()->as_array();
        $price = 0;
        foreach ($arr as $row)
        {
            $price += Model_Member_Order::order_total_price($row['id'],$row);
        }
        $out['total_price'] = $price;

        $where1=$where." AND a.status in(2,5,6)";
        //支付订单数
        $sql = "SELECT a.* FROM `sline_member_order` a LEFT JOIN `sline_member` b ON(a.memberid=b.mid)  WHERE $where1  ORDER BY a.addtime DESC ";
        $totalSql = "SELECT count(*) as dd " . strchr($sql, " FROM");
        $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by
        $totalN = DB::query(1, $totalSql)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? intval($totalN[0]['dd']) : 0;
        $out['pay_num'] = $totalNum;

        $arr = DB::query(1, $sql)->execute()->as_array();
        $price = 0;
        foreach ($arr as $row)
        {
            $price += Model_Member_Order::order_total_price($row['id'],$row);
        }
        $out['pay_price'] = $price;

        $where2=$where." AND a.status in(0,1)";
        //支付订单数
        $sql = "SELECT a.* FROM `sline_member_order` a LEFT JOIN `sline_member` b ON(a.memberid=b.mid)  WHERE $where2  ORDER BY a.addtime DESC ";
        $totalSql = "SELECT count(*) as dd " . strchr($sql, " FROM");
        $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by
        $totalN = DB::query(1, $totalSql)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? intval($totalN[0]['dd']) : 0;
        $out['unpay_num'] = $totalNum;

        $arr = DB::query(1, $sql)->execute()->as_array();
        $price = 0;
        foreach ($arr as $row)
        {
            $price += Model_Member_Order::order_total_price($row['id'],$row);
        }
        $out['unpay_price'] = $price;

        echo json_encode($out);
    }

    /*
     * 会员订单
     * */
    public function action_order_list()
    {
        $mid = $this->params['mid'];//会员id.
        $this->assign('action','order_list');
        $this->assign('mid',$mid);
//        sort
        $action = $this->params['act'];
        $this->assign('all_modle',Model_Model::get_all_pdt_models(1));
        $this->assign('order_status',Model_Member_Order::$order_status);
        if (empty($action))  //显示列表
        {
            $this->display('stourtravel/member/order_list');
        }
        else if ($action == 'read')    //读取列表
        {
            $page = isset($_GET['page'])&& intval($_GET['page'])>0 ? intval($_GET['page']) : 1;
            $pagesize = isset($_GET['limit']) ? intval($_GET['limit']) : 15;
            $typeid = isset($_GET['typeid'])? intval($_GET['typeid']): 0;
            $status = $_GET['status'];

            //排序
            $sort = json_decode($_GET['sort'],true);
            if(empty($sort)){
                //默认排序
                $order_by=' addtime asc ';
            }else{
                $order_by=" {$sort[0]['property']} {$sort[0]['direction']}";
            }

            $page = $page ? $page : 1;
            $offset = (intval($page) - 1) * $pagesize;
            $value_arr = array();
            if (!empty($mid)) {
                $where = "WHERE a.memberid='$mid'";
            } else {
                $where = "WHERE a.memberid>0";
            }
            if (!empty($typeid)) {
                $where .= " AND a.typeid=$typeid";
            }
            $query = DB::select('id')->from('model');
            if (!empty($status))
            {
                $where .= " AND a.status=$status";
            }
            //模块
            $typeids = array();
            $model = $query->execute()->as_array();
            foreach ($model as $v) {
                array_push($typeids, $v['id']);
            }
            if ($typeids) {
                $typeids = implode(',', $typeids);
                $where .= " and typeid in($typeids)";
            }
            //按手机号进行查询
            if (!empty($linktel)) {
                $where .= " AND (a.linktel=:linktel OR b.mobile=:linktel)";
                $value_arr[':linktel'] = $linktel;
            }
            $sql = "SELECT a.* FROM `sline_member_order` a LEFT JOIN `sline_member` b ON(a.memberid=b.mid)  $where   ORDER BY {$order_by} ";
            //计算总数
            $totalSql = "SELECT count(*) as dd " . strchr($sql, " FROM");
            $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by
            $totalN = DB::query(1, $totalSql)->parameters($value_arr)->execute()->as_array();
            $totalNum = $totalN[0]['dd'] ? intval($totalN[0]['dd']) : 0;
            $sql .= "LIMIT {$offset},{$pagesize}";
            $arr = DB::query(1, $sql)->parameters($value_arr)->execute()->as_array();
            foreach ($arr as &$v) {
                $orderInfo = Model_Member_Order::order_info($v['ordersn']);
                $productInfo = St_Product::get_product_info($v['typeid'], $v['productautoid']);
                $model = ORM::factory('model', $v['typeid']);
                $model_info = Model_Model::getModuleInfo($v['typeid']);
                $v['modulename'] = $model_info['modulename'];
                $v['pinyin'] = $model_info['pinyin'];
                $table = $model->maintable;
                $v['statusname'] = Model_Member_Order::$order_status[$v['status']];
                if ($table && class_exists('Model_' . $table)) {
                    $infoModel = 'Model_' . $table;
                    if (is_callable(array($infoModel, 'pay_status'))) {
                        $infoModel = new $infoModel();
                        $status = $infoModel::pay_status();

                        foreach ($status as $s) {
                            if ($s['status'] == $v['status']) {
                                $v['statusname'] = $s['status_name'];
                                break;
                            }
                        }
                    }
                }
                $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
                $v['producturl'] = $productInfo['url'];
                $v['litpic'] = $productInfo['litpic'];
                $v['dingnum'] = $v['dingnum'] + $v['childnum'] + $v['oldnum'] + $v['people4_num'] + $v['people5_num'] + $v['people6_num'];
                $v['totalprice'] = $orderInfo['payprice'];
                $v['price'] = $v['price'] == '0' ? $v['childprice'] : $v['price'];
            }
            $data['list'] = $arr;
            $data['total'] = $totalNum;
            echo json_encode($data);
        }
    }

    public function action_wallet_list()
    {
        $action = $this->params['act'];
        if(empty($action)){
            $wallet = Model_Wallet::get_wallet_balance($this->params['mid']);

            $this->assign('mid',$this->params['mid']);
            $this->assign('wallet',$wallet);
            $this->assign('action','wallet_list');
            $this->display('stourtravel/member/wallet_list');
        }elseif($action=='read'){
            $params = [
                'start'     => Arr::get($_GET, 'start'),
                'limit'     => Arr::get($_GET, 'limit'),
                'type'      => Arr::get($_GET, 'type'),
                'member_id' => $this->params['mid'],
            ];

            $list = Model_Wallet::get_wallet_log($params);

            echo json_encode($list);
        }

    }

    public function action_wallet_balance()
    {
        $action = $this->params['act'];
        if (empty($action)) {
            $type = $this->params['type'];

            $this->assign('type', $type);
            $this->assign('mid', $this->params['mid']);
            $this->display('stourtravel/member/wallet_balance');
        } elseif ($action == 'save') {
            $type   = Arr::get($_POST, 'type');
            $params = [
                'memberid'   => Arr::get($_POST, 'mid'),
                'describe'   => Arr::get($_POST, 'describe'),
                'use_amount' => Arr::get($_POST, 'use_amount'),
                'source'     => 1,
            ];

            $db = Database::instance();
            $db->begin();
            try {
                $types = $type == 1 ? 6 : 5;
                Model_Wallet::wallet_log($params, $params, $types);

                $wallet_member = DB::select()->from('wallet_member')->where('member_id', '=', $params['memberid'])->execute()->current();
                if (!$wallet_member) {
                    $wallet_member = [
                        'member_id'     => $params['memberid'],
                        'amount'        => 0,
                        'use_amount'    => 0,
                        'remain_amount' => 0,
                        'modtime'       => time()
                    ];
                    $id = DB::insert('wallet_member', array_keys($wallet_member))->values(array_values($wallet_member))->execute();
                    $wallet_member['id'] = $id[0];
                }
                if($wallet_member['amount']<=0 && $type==1){
                    throw new Exception('余额不足，不可继续扣除！');
                }
                $data['modtime'] = time();
                if ($type == 1) {
                    $data['amount']        = bcsub($wallet_member['amount'], $params['use_amount'], 2);
                    $data['remain_amount'] = bcsub($wallet_member['remain_amount'], $params['use_amount'], 2);
                } else {
                    $data['amount']        = bcadd($wallet_member['amount'], $params['use_amount'], 2);
                    $data['remain_amount'] = bcadd($wallet_member['remain_amount'], $params['use_amount'], 2);
                }

                DB::update('wallet_member')->set($data)->where('id', '=', $wallet_member['id'])->execute();

                $res = [
                    'status' => true,
                    'msg'    => '操作成功'
                ];

                $db->commit();
            } catch (Exception $e) {
                $db->rollback();
                $res = [
                    'status' => false,
                    'msg'    => $e->getMessage()
                ];
            }

            echo json_encode($res);
        }

    }

    public function action_modify_level()
    {
        $mid        = $this->params['mid'];
        $grade_id   = DB::select()->from('member')->where('mid', '=', $mid)->execute()->get('grade_id');
        $level_list = DB::select()->from('member_grade')->where('id', '!=', $grade_id)->execute()->as_array();

        $this->assign('mid', $mid);
        $this->assign('level_list', $level_list);
        $this->display('stourtravel/member/level');
    }

    public function action_ajax_update_level()
    {
        $mid               = $this->params['mid'];
        $level_id          = Arr::get($_POST, 'level_id');
        $grade_expire_time = Arr::get($_POST, 'grade_expire_time');
        $day               = Arr::get($_POST, 'day');
        if ($grade_expire_time == 1) {
            $grade_expire_time = time() + 86400 * $day;
        }
        $grade_name = DB::select()->from('member_grade')->where('id', '=', $level_id)->execute()->get('name');
        DB::update('member')->set([
            'grade_id'          => $level_id,
            'grade_name'        => $grade_name,
            'grade_expire_time' => $grade_expire_time,
        ])->where('mid', '=', $mid)->execute();

        echo json_encode(['name' => $grade_name]);
    }
}